<?php


namespace app\admin\controller\purchase;


use app\common\model\PurchaseGoodsIn;

class GoodsTotal extends \app\admin\controller\Base
{
    public function Index(){
        $limit = input('get.limit');
        $list = PurchaseGoodsIn::with('getGoodsOut')->paginate($limit)->each(function (&$item){
            $arr = [];
            if ($item['getGoodsOut']){
                foreach ($item['getGoodsOut'] as $v){
                    $arr[date("Y-m", strtotime($v['receive_time']))] = $v;
                }
            }
            //上个月的日期
            $lastMonth = date("Y-m",strtotime(date("Y-m-01")." -1 month"));
            //这个月
            $month = date('Y-m');
            $lastCount = $item['stock'] - array_sum(array_column($arr[$lastMonth]??[],'receive_num'));
            $item['last'] = [
                'count'=>$lastCount,
                'price'=>$item['price'],
                'total'=>$lastCount*$item['price']
            ];
            //本月剩余
            $nowCount = $lastCount - array_sum(array_column((array)$arr[$month]??[],'receive_num'));
            $item['nowSurplus'] = [
                'count'=>$nowCount,
                'price'=>$item['price'],
                'total'=>$nowCount*$item['price']
            ];
            //本月入库
            $item['enter'] = $month == date("Y-m", strtotime($item['add_time'])) ?
                [
                'count'=>$item['stock'],
                'price'=>$item['price'],
                'total'=>$item['total']
                ]:[
                    'count'=>0,
                    'price'=>$item['price'],
                    'total'=>0
                ];
            //本月出库
            $item['out'] = [
                'count'=>array_sum(array_column($arr[$lastMonth]??[],'receive_num')),
                'price'=>$item['price'],
                'total'=>array_sum(array_column($arr[$lastMonth]??[],'receive_num'))*$item['price']
            ];
        });
        return $this->getAuto($this->fetch(''), ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]]);
    }

}